package com.ias.log.util;

import org.slf4j.MDC;

import java.util.UUID;

/**
 * 追踪ID工具类
 * 
 * @author ias
 * @since 2024
 */
public class TraceUtil {

    private static final String TRACE_ID_KEY = "traceId";

    /**
     * 获取追踪ID
     *
     * @return 追踪ID
     */
    public static String getTrace() {
        String traceId = MDC.get(TRACE_ID_KEY);
        if (traceId == null || traceId.isEmpty()) {
            traceId = generateTraceId();
            MDC.put(TRACE_ID_KEY, traceId);
        }
        return traceId;
    }

    /**
     * 设置追踪ID
     *
     * @param traceId 追踪ID
     */
    public static void setTrace(String traceId) {
        if (traceId != null && !traceId.isEmpty()) {
            MDC.put(TRACE_ID_KEY, traceId);
        }
    }

    /**
     * 清除追踪ID
     */
    public static void clearTrace() {
        MDC.remove(TRACE_ID_KEY);
    }

    /**
     * 生成追踪ID
     *
     * @return 追踪ID
     */
    public static String generateTraceId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}

